import socket
import threading

not_found_msg = """<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL {path} was not found on this server.</p>
</body></html>"""

# 1.编写一个TCP服务端程序
# 创建TCP服务端socket
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置端口号复用，程序退出端口立即释放
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
# 绑定端口号
tcp_server_socket.bind(('', 80))
# 设置监听
tcp_server_socket.listen(128)
# 循环接收客户端的连接请求
while True:
    # 等待接收客户端的连接请求
    conn_client_socket, ip_port = tcp_server_socket.accept()


    def handle_client_request(conn_socket):
        # 2.获取浏览器发送的HTTP请求报文数据
        client_request_data = conn_socket.recv(4096).decode()
        if not client_request_data:
            conn_socket.close()
            return

        # 3.获取用户请求资源的路径
        path = client_request_data.splitlines()[0].split()[1]
        if path == '/':
            path = '/index.html'

        try:
            # 4.根据请求资源的路径，读取指定文件的数据
            with open('static' + path, 'rb') as f:
                file_data = f.read()
        except FileNotFoundError:
            # 5.判断请求的文件在服务端不存在，组装404状态的响应报文，发送给浏览器
            response_line = "HTTP/1.1 404 Not Found\r\n"
            response_header = "Server: Python Web\r\n"
            response_body = not_found_msg.format(path=path)
            response_data = (response_line + response_header + '\r\n' + response_body).encode()
            conn_socket.send(response_data)
        else:
            # 响应行
            response_line = "HTTP/1.1 200 OK\r\n"
            # 响应头
            response_header = "Server: Python Web\r\n"
            # 响应体
            response_body = file_data
            # 组装HTTP格式的响应报文
            response_data = (response_line + response_header + '\r\n').encode() + response_body
            conn_socket.send(response_data)
        finally:
            # 6.HTTP响应报文数据发送完成后，关闭服务于客户端的套接字
            conn_socket.close()


    # 开辟子线程并执行对应的任务
    t = threading.Thread(target=handle_client_request, args=(conn_client_socket,))
    t.start()
